package com.aaa.bitmapcache;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

public class ImageResize {
    private static final String TAG = "ImageResize";

    /**
     * 返回压缩图片
     *
     * @param context
     * @param id       The resource id of the image data
     * @param maxW     ViewWidth
     * @param maxH     ViewHeight
     * @param hasAlpha
     * @return
     */
    public static Bitmap resizeBitmap(Context context, int id, int maxW, int maxH, boolean hasAlpha, Bitmap reusable) {

        Resources resources = context.getResources();

        BitmapFactory.Options options = new BitmapFactory.Options();
        // 设置inJustDecodeBounds为true后，再去解析，就只解析 outXXX 参数，比如outWidth等，而decodeResource()返回null
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(resources, id, options);

        int w = options.outWidth;
        int h = options.outHeight;
        Log.i(TAG, "resizeBitmap: inDensity=" + options.inDensity);
        Log.i(TAG, "resizeBitmap: inTargetDensity=" + options.inTargetDensity);
        Log.i(TAG, "resizeBitmap: densityDpi=" + resources.getDisplayMetrics().densityDpi);
        Log.i(TAG, "resizeBitmap: 复用=" + reusable);
        // inSampleSize是图片解码缩放比，如值为2，则加载图片的宽高是原来的 1/2，整个图片所占内存的大小就是原图的 1/4
        options.inSampleSize = calcuteInSampleSize(w, h, maxW, maxH);

        if (!hasAlpha) {
            options.inPreferredConfig = Bitmap.Config.RGB_565;
        }

        // inMutable 设为true 表示易变，才能复用
        options.inMutable = true;
        options.inBitmap = reusable;

        // 恢复inJustDecodeBounds为false，才能让decodeResource()返回非null
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeResource(resources, id, options);

    }

    /**
     * 计算 缩放系数
     *
     * @param w    BitmapWidth
     * @param h    BitmapHeight
     * @param maxW ViewWidth
     * @param maxH ViewHeight
     * @return inSampleSize是图片解码缩放比，如值为2，则加载图片的宽高是原来的 1/2，整个图片所占内存的大小就是原图的 1/4
     */
    private static int calcuteInSampleSize(int w, int h, int maxW, int maxH) {
        int inSampleSize = 1;
        if (w > maxW && h > maxH) {
            inSampleSize = 2;
            while (w / inSampleSize > maxW && h / inSampleSize > maxH) {
                inSampleSize *= 2;
            }
        }
        return inSampleSize;
    }
}
